#include "stdafx.h"
#include "DisplaymodeDialog.h"

#include "resource.h"

DisplayModesPtr g_modes;
VideoSettings* g_settings;

LRESULT CALLBACK DlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	HWND combobox_handle = GetDlgItem(hWndDlg, IDC_DISPMODE_COMBO);
	HWND fullscreen_handle = GetDlgItem(hWndDlg, IDC_FULLSCREEN_CHECK);
	HWND vsync_handle = GetDlgItem(hWndDlg, IDC_VSYNC_CHECK);
	uint mode_count = g_modes->getModeCount();
	switch(Msg)
	{
	case WM_INITDIALOG:
		
		for(uint i = 0; i < mode_count; ++i)
		{
			SendMessage(combobox_handle, CB_ADDSTRING, 0, 
				reinterpret_cast<LPARAM>(g_modes->getMode(i).getDescription().c_str()));
		}
		SendMessage(combobox_handle, CB_SETCURSEL, g_modes->getDesktopMode(), 0);
		SendMessage(fullscreen_handle, BM_SETCHECK, BST_CHECKED, 0);
		SendMessage(vsync_handle, BM_SETCHECK, BST_CHECKED, 0);
		return true;

	case WM_COMMAND:
		switch(wParam)
		{
		case IDOK:
			bool fullscreen = SendMessage(fullscreen_handle, BM_GETCHECK, 0, 0) == BST_CHECKED;
			bool vsync = SendMessage(vsync_handle, BM_GETCHECK, 0, 0) == BST_CHECKED;
			uint selected_id = SendMessage(combobox_handle, CB_GETCURSEL, 0, 0);
			DisplayMode& selected = g_modes->getMode(selected_id);
			(*g_settings)["ScreenWidth"] = selected.getWidth();
			(*g_settings)["ScreenHeight"] = selected.getHeight();
			(*g_settings)["RefreshRate"] = selected.getRefreshRate();
			(*g_settings)["Fullscreen"] = fullscreen;
			(*g_settings)["VSync"] = vsync;
			EndDialog(hWndDlg, IDOK);
			return true;
		}
		break;

	case WM_CLOSE:
		EndDialog(hWndDlg, 0);
		return true;
	}

	return false;
}

bool showDisplaymodeDialog(DisplayModesPtr modes, VideoSettings& settings)
{
	g_modes = modes;
	g_settings = &settings;
	int ret = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, reinterpret_cast<DLGPROC>(DlgProc));
	if(ret == IDOK)
		return true;
	return false;
}
